package com.synv.flashcard;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.synv.entity.Category;
import com.synv.entity.FlashCard;
import com.synv.flashcard.R.color;
import com.synv.util.DataBaseHelper;
import com.synv.util.Utils;
import com.synv.util.WebParserUtils;

public class ContentActivity extends Activity {

	//"file:///sdcard/flashcard/";
	public static final Integer SCREEN_FLIPPER_FRIST = 0;
	public static final Integer SCREEN_FLIPPER_SECOND = 1;
	private ViewFlipper viewFlipper;
    private float lastX;
    private float lastY;
    private Uri uri;
    private MediaPlayer mPlayer;
    private List<FlashCard> flashcards;
    private Integer currentCard;
    private FlashCard card1, card2;
    private CheckBox bookmark;
    private Button btnPlay, btnGoHome;
    private LinearLayout llMeaning1, llMeaning2, llGuide1;
    private TextView txtWord1, txtWord2, txtPhonetic1, txtPhonetic2, txtWordRelated1, txtWordRelated2, txtExamples1, txtExamples2, txtMeaning1, txtMeaning2;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_content);
		if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		}
		
		Intent intent = getIntent();
		Integer categorySeq = intent.getIntExtra("categorySeq", 1);
		String categoryName = intent.getStringExtra("categoryName");
		if(categoryName == null || "".equals(categoryName)) categoryName = "English Flash Card";
		
		ActionBar actionBar = getActionBar();
		actionBar.setBackgroundDrawable(new ColorDrawable(color.header));
		actionBar.setTitle(categoryName);
		
		viewFlipper = (ViewFlipper) findViewById(R.id.view_flipper);
		txtWord1 = (TextView) findViewById(R.id.txtWord1);
		txtWord2 = (TextView) findViewById(R.id.txtWord2);
		txtPhonetic1 = (TextView) findViewById(R.id.txtPhonetic1);
		txtPhonetic2 = (TextView) findViewById(R.id.txtPhonetic2);
		txtWordRelated1 = (TextView) findViewById(R.id.wordRelated1);
		txtWordRelated2 = (TextView) findViewById(R.id.wordRelated2);
		txtExamples1 = (TextView) findViewById(R.id.examples1);
		txtExamples2 = (TextView) findViewById(R.id.examples2);
		txtMeaning1 = (TextView) findViewById(R.id.txtMeaning1);
		txtMeaning2 = (TextView) findViewById(R.id.txtMeaning2);
		llMeaning1 = (LinearLayout) findViewById(R.id.llMeaning1);
		llMeaning2 = (LinearLayout) findViewById(R.id.llMeaning2);
		llGuide1 = (LinearLayout) findViewById(R.id.llGuide1);
		bookmark = (CheckBox) findViewById(R.id.bookmark);
		btnPlay = (Button) findViewById(R.id.play);
		btnGoHome = (Button) findViewById(R.id.goHome);
		
		btnPlay.setOnClickListener(new OnClickListener() {
			 
		    public void onClick(View v) {
		    	if(flashcards == null || flashcards.size() == 0) return;
		    	String word = flashcards.get(currentCard).getWord();
		    	File file = new File(WebParserUtils.DEFAULT_FOLDER + word + ".mp3");
		    	Context ctx = v.getContext();
		    	if(!file.exists())  {
		    		if(!Utils.checkInternetConnection(ctx)) {
		    			AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
		    			builder.setMessage("Không có kết nối Internet!")
		    			       .setCancelable(false)
		    			       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		    			           public void onClick(DialogInterface dialog, int id) {
		    			                //do things
		    			           }
		    			       });
		    			AlertDialog alert = builder.create();
		    			alert.show();
		    			return;
		    		}
		    		WebParserUtils.storeMp3(word);
		    		file = new File(WebParserUtils.DEFAULT_FOLDER + word + ".mp3");
		    	}
		    	if(!file.exists()) return;
		    	uri = Uri.parse(WebParserUtils.DEFAULT_FOLDER + word + ".mp3");
		    	mPlayer = new MediaPlayer();
		        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		        try {
		            mPlayer.setDataSource(getApplicationContext(), uri);
		        } catch (IllegalArgumentException e) {
		            Toast.makeText(getApplicationContext(), "Không có dữ liệu!", Toast.LENGTH_SHORT).show();
		        } catch (SecurityException e) {
		            Toast.makeText(getApplicationContext(), "Không có dữ liệu!", Toast.LENGTH_SHORT).show();
		        } catch (IllegalStateException e) {
		            Toast.makeText(getApplicationContext(), "Không có dữ liệu!", Toast.LENGTH_SHORT).show();
		        } catch (IOException e) {
		            e.printStackTrace();
		        }
		        try {
		            mPlayer.prepare();
		        } catch (IllegalStateException e) {
		            Toast.makeText(getApplicationContext(), "Không có dữ liệu!", Toast.LENGTH_SHORT).show();
		        } catch (IOException e) {
		            Toast.makeText(getApplicationContext(), "Không có dữ liệu!", Toast.LENGTH_SHORT).show();
		        }
		        mPlayer.start();
		    }
		});
		
		btnGoHome.setOnClickListener(new OnClickListener() {
			 
		    public void onClick(View v) {
		    	//if(flashcards == null || flashcards.size() == 0) return;
		    	goHome();
		    }
		});
		
		bookmark.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(flashcards == null || flashcards.size() == 0) return;
				updateBookmark(isChecked);
			}
		});
		
		initial(categorySeq);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.content, menu);
		return true;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		/*DataBaseHelper myDbHelper = new DataBaseHelper(this);
		FlashCard flashcard = flashcards.get(currentCard);
		Cursor c = myDbHelper.getReadableDatabase().query("flashcard", null, "word = '" + flashcard.getWord() + "'", null, null, null, "seq");
		flashcard = new FlashCard(c.getInt(0), c.getString(1), 
					c.getInt(2), c.getString(3), c.getString(4), 
					c.getString(5), c.getString(6), c.getString(7), 
					c.getInt(8), c.getInt(9), c.getInt(10), c.getString(11));
		myDbHelper.close();
		new FlashCard(c.getInt(0), c.getString(1), 
					c.getInt(2), c.getString(3), c.getString(4), 
					c.getString(5), c.getString(6), c.getString(7), 
					c.getInt(8), c.getInt(9), c.getInt(10), c.getString(11));*/
	};
	
	private void initial(Integer categorySeq) {
		try {
			DataBaseHelper myDbHelper = new DataBaseHelper(this);
			currentCard = 0;
			Cursor c = myDbHelper.getReadableDatabase().query("flashcard", null, "Category like '%," + categorySeq + ",%'", null, null, null, "word");
			if(categorySeq == Category.MARKED_CATEGORY) {
				c.close();
				c = myDbHelper.getReadableDatabase().query("flashcard", null, "Bookmark = 1", null, null, null, "word");
			}
	 		
	 		c.moveToFirst();
	 		flashcards = new ArrayList<FlashCard>();
	 		while(!c.isAfterLast()) {
	 			FlashCard flashcard = new FlashCard(c.getInt(0), c.getString(1), 
	 					c.getInt(2), c.getString(3), c.getString(4), 
	 					c.getString(5), c.getString(6), c.getString(7), 
	 					c.getInt(8), c.getInt(9), c.getInt(10), c.getString(11));
	 			flashcards.add(flashcard);
	 			c.moveToNext();
	 		}
	 		c.close();
	 		myDbHelper.close();
		 	if(flashcards.size() > 0) {
		 		populateData(0);
		 	}
		} catch (Exception ex) {
			Log.e("Init content", ex.getMessage());
		}
	}

	private void populateData(Integer cardOrder) {
		if(cardOrder == SCREEN_FLIPPER_FRIST) {
			card1 = flashcards.get(currentCard);
			uri = Uri.parse(WebParserUtils.DEFAULT_FOLDER + card1.getAudio());
			txtWord1.setText(card1.getWord() + getWordType(card1.getWordType()));
			if(card1.getPhonetic() == null || card1.getPhonetic().isEmpty()) {
				txtPhonetic1.setVisibility(TextView.INVISIBLE);
			} else {
				txtPhonetic1.setText(card1.getPhonetic());
				txtPhonetic1.setVisibility(TextView.VISIBLE);
			}
			if(card1.getWordRelated() == null || card1.getWordRelated().isEmpty()) {
				txtWordRelated1.setVisibility(TextView.INVISIBLE);
			} else {
				txtWordRelated1.setText(card1.getWordRelated());
				txtWordRelated1.setVisibility(TextView.VISIBLE);
			}
			if(card1.getExamples() == null || card1.getExamples().isEmpty()) {
				txtExamples1.setVisibility(TextView.INVISIBLE);
			} else {
				txtExamples1.setText(card1.getExamples());
				txtExamples1.setVisibility(TextView.VISIBLE);
			}
			txtMeaning1.setText(card1.getMeaning());
			if(card1.getBookmark() != null && card1.getBookmark() > 0) {
				bookmark.setChecked(true);
       	 	} else {
       	 		bookmark.setChecked(false);
       	 	}
		} else {
			card2 = flashcards.get(currentCard);
			uri = Uri.parse(WebParserUtils.DEFAULT_FOLDER + card2.getAudio());
			txtWord2.setText(card2.getWord() + getWordType(card2.getWordType()));
			if(card2.getPhonetic() == null || card2.getPhonetic().isEmpty()) {
				txtPhonetic2.setVisibility(TextView.INVISIBLE);
			} else {
				txtPhonetic2.setText(card2.getPhonetic());
				txtPhonetic2.setVisibility(TextView.VISIBLE);
			}
			if(card2.getWordRelated() == null || card2.getWordRelated().isEmpty()) {
				txtWordRelated2.setVisibility(TextView.INVISIBLE);
			} else {
				txtWordRelated2.setText(card2.getWordRelated());
				txtWordRelated2.setVisibility(TextView.VISIBLE);
			}
			if(card2.getExamples() == null || card2.getExamples().isEmpty()) {
				txtExamples2.setVisibility(TextView.INVISIBLE);
			} else {
				txtExamples2.setText(card2.getExamples());
				txtExamples2.setVisibility(TextView.VISIBLE);
			}
			txtMeaning2.setText(card2.getMeaning());
			if(card2.getBookmark() != null && card2.getBookmark() > 0) {
				bookmark.setChecked(true);
       	 	} else {
       	 		bookmark.setChecked(false);
       	 	}
		}
	}
	
	private void updateBookmark(Boolean isChecked) {
		DataBaseHelper myDbHelper = new DataBaseHelper(this);
		FlashCard flashCard = flashcards.get(currentCard);
		try {
	 		Integer checked = isChecked ? 1 : 0;
	 		flashCard.setBookmark(checked);
	 		myDbHelper.getReadableDatabase().execSQL("UPDATE flashcard SET Bookmark = " + checked +" WHERE Seq = " + flashCard.getSeq());
	 		myDbHelper.close();
	 	} catch(Exception sqle){
	 		System.out.println(sqle.getMessage());
	 	}
	}
	
	private String getWordType(Integer wordType) {
		String type = "";
		if(wordType >= FlashCard.PREP) {
			type = "(pre)";
			wordType = wordType - FlashCard.PREP;
		}
		if(wordType >= FlashCard.ADV) {
			type = "(adv)" + type;
			wordType = wordType - FlashCard.ADV;
		}
		if(wordType >= FlashCard.ADJ) {
			type = "(adj)" + type;
			wordType = wordType - FlashCard.ADJ;
		}
		if(wordType >= FlashCard.VERB) {
			type = "(v)" + type;
			wordType = wordType - FlashCard.VERB;
		}
		if(wordType >= FlashCard.NOUN) {
			type = "(n)" + type;
			wordType = wordType - FlashCard.NOUN;
		}
		return type;
	}

	public boolean onTouchEvent(MotionEvent touchevent) 
    {
	     switch (touchevent.getAction())
	     {
	             case MotionEvent.ACTION_DOWN: 
	             {
	                 lastX = touchevent.getX();
	                 lastY = touchevent.getY();
	                 break;
	            }
	             case MotionEvent.ACTION_UP: 
	             {
	            	 llGuide1.setVisibility(View.GONE);
	            	 //check if no word in list
	            	 if(flashcards.size() == 0) return false;
	            	 
	                 float currentX = touchevent.getX();
	                 float currentY = touchevent.getY();
	                 float deltaX = currentX - lastX;
	                 float deltaY = currentY - lastY;
	                 
	                 //if swip horizotal
	                 if(Math.abs(deltaX) > Math.abs(deltaY)) {
	                	 llMeaning1.setVisibility(TextView.GONE);
	                     llMeaning2.setVisibility(TextView.GONE);
	                     
	                     if (lastX < currentX) 
	                     {
	                    	 viewFlipper.setInAnimation(this, R.anim.slide_left_in);
	                         viewFlipper.setOutAnimation(this, R.anim.slide_right_out);
	                         if(currentCard == 0) {
	                    		 currentCard = flashcards.size() - 1;
	                    	 } else {
	                    		 currentCard--;
	                    	 }
	                         if (viewFlipper.getDisplayedChild() == 0) {
	                        	 populateData(SCREEN_FLIPPER_SECOND);
	                             viewFlipper.showPrevious();
	                         } else {
	                        	 populateData(SCREEN_FLIPPER_FRIST);
	                             viewFlipper.showNext();
	                         }
	                     }
	                     if (lastX > currentX)
	                     {
	                    	 viewFlipper.setInAnimation(this, R.anim.slide_right_in);
	                         viewFlipper.setOutAnimation(this, R.anim.slide_left_out);
	                         if(currentCard == flashcards.size() - 1) {
	                    		 currentCard = 0;
	                    	 } else {
	                    		 currentCard++;
	                    	 }
	                         if (viewFlipper.getDisplayedChild() == 1) {
	                        	 populateData(SCREEN_FLIPPER_FRIST);
	                        	 viewFlipper.showNext();
	                         } else {
	                        	 populateData(SCREEN_FLIPPER_SECOND);
	                        	 
	                        	 viewFlipper.showPrevious();
	                         }
	                     }
	                 } else {   //swipe vertical
	                     if (lastY < currentY) 
	                     {
	                    	 llMeaning1.setVisibility(TextView.GONE);
	                         llMeaning2.setVisibility(TextView.GONE);
	                     }
	                    
	                     if (lastY > currentY)
	                     {
	                    	 Animation slideUpIn = AnimationUtils.loadAnimation(this, R.anim.slide_up_in);
	                    	 if(viewFlipper.getDisplayedChild() == 0) {
	                    		 llMeaning1.startAnimation(slideUpIn);
	                        	 llMeaning1.setVisibility(TextView.VISIBLE);
	                         } else {
	                        	 llMeaning2.startAnimation(slideUpIn);
	                        	 llMeaning2.setVisibility(TextView.VISIBLE);
	                         }
	                      }
	                 }
	                 break;
	             }
	     }
	     return false;
    }
	
	private void goHome() {
		/*Intent contentScreen = new Intent(this, WordDetailActivity.class);
		contentScreen.putExtra("word", flashcards.get(currentCard).getWord());
		startActivity(contentScreen);*/
		finish();
	}
}
